/**
 * 
 */
package org.dragonfire.dasm.directives;

import java.util.ArrayList;
import java.util.Arrays;

import org.dragonfire.dasm.Command;
import org.dragonfire.dasm.Listing;
import org.dragonfire.dasm.DirectiveManager.Directive;

/**
 * Creates a block of bytes<br />
 * <br />
 * Format:<br />
 * <code>#FILL <i>&lt;size&gt;</i>[,<i>&lt;value&gt;</i>]</code><br />
 * <br />
 * Parameters:<br />
 * <table>
 * <tr>
 * <td><code>size</code></td>
 * <td>(Integer) The size of the block in number of bytes.</td>
 * </tr>
 * <tr>
 * <td><code>value</code></td>
 * <td>(Integer, Optional) The value with which to fill each byte. The default
 * is <code>0xFF</code> is this parameter is omitted.</td>
 * </tr>
 * </table><br />
 * Errors:<br />
 * <table>
 * <tr>
 * <td><code>ERROR_NOT_ENOUGH_ARGS</code></td>
 * <td>Thrown if <code>size</code> is undefined.</td>
 * </tr>
 * <tr>
 * <td><code>ERROR_INT_REQUIRED</code></td>
 * <td>Thrown if <code>size</code> or <code>value</code> is not an integer</td>
 * </tr>
 * </table>
 * 
 * @author Darth Android
 * @version 2.0
 * @see Block
 */
public class Fill extends Directive {

	/**
	 * {@inheritDoc}
	 */
	@Override
	public ArrayList<Listing> pass1(org.dragonfire.dasm.Command c) {
		ArrayList<Listing> list = new ArrayList<Listing>();
		int size = evalInt(c.getParam(0));
		Listing l = new Listing(size, c);
		list.add(l);
		return list;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void pass2(Listing lst, Command c) {
		/*
		 * calculate the value during the second pass in case a label was used
		 * and had to be forward-calculated
		 */
		int val = 255;
		if (getParam("fill-value") != null)
			val = evalInt(getParam("fill-value"));
		if (c.getParams().length > 1) {
			val = evalInt(c.getParams()[1]);
		}
		if (val != (val & 0xFF))
			warn("WARN_TRUNCATED_DATA", val, "2nd");
		Arrays.fill(lst.getMCode(), (byte) val);
	}
}
